const henglang = {
	host:'https://api.gdhenglang.com/',
	app_key:'kpXaxw3HAcShy3dv2d43J5SCjcmVss211ZT4CVR543Df',
	check_update:true,
	showToast:function(title,duration){
		uni.showToast({
			icon: 'none',
			title: title,
			mask: true,
			duration:duration?duration:3000
			//success:success(e) 
		})
	},
	get:function(url,param,check_token,success,fail){
		let request = {
			url:henglang.host+url,
			method:'GET',
			header:{'app-key': henglang.app_key},
			data:param,
			success:(res) => {
				if(res.data.statusCode == '404'){
					henglang.showToast(res.data.data);
					return false;
				}
				if(typeof success == 'function') success(res);
			},
			fail:(res) => {
				if(typeof fail == 'function') fail(res);
			}
		};
		//#ifdef APP-PLUS
		request.header.os = plus.os.name;
		request.header.version = plus.runtime.version;
		//#endif
		let token = uni.getStorageSync('token');
		if(check_token == true && !token){
			uni.showToast({
				title:'请先登录后再操作',
				icon:'none',
				duration:3000,
				success() {
					uni.navigateTo({
						url: '/pages/user/login'
					});
				}
			})
			return false;
		}
		request.header['access-token'] = token?token:'';
		uni.request(request);
	},
	post:function(url,data,check_token,success,fail){
		let request = {
			url:henglang.host+url,
			method:'POST',
			header:{'app-key': henglang.app_key},
			success:(res) => {
				if(res.data.statusCode == '404'){
					henglang.showToast(res.data.data);
					return false;
				}
				if(typeof success == 'function') success(res);
			},
			fail:(res) => {
				if(typeof fail == 'function') fail(res);
			}
		};
		//#ifdef APP-PLUS
		request.header.os = plus.os.name;
		request.header.version = plus.runtime.version;
		//#endif
		if(data) request.data = data;
		let token = uni.getStorageSync('token');
		if(check_token == true && !token){
			uni.showToast({
				title:'请先登录后再操作',
				icon:'none',
				duration:3000,
				success() {
					uni.navigateTo({
						url: '/pages/user/login'
					});
				}
			})
			
			return false;
		}
		request.header['access-token'] = token?token:'';
		uni.request(request);
	},
	checkLogin:function(){
		return uni.getStorageSync('token')?true:false;
	},
	checkPhone:function(e) {
	    let rPhone = /^1[3-9][0-9]\d{8}$/g;
	    if (rPhone.test(e)) {
	        return true;
	    } else {
	        return false;
	    }
	},
	checkCode:function(e) {
	    let rCode = /^\d{6}$/g;
	    if (rCode.test(e)) {
	        return true;
	    } else {
	        return false;
	    }
	},
	countDown:function(that, name, time) {
		let timer = null;
		that[name] = time;
		timer = setInterval(() => {
			that[name] = --that[name];
			if (!that[name]) {
				that[name] = false;
				clearInterval(timer);
			}
		}, 1000)
	},
	isGoodsTpye:function(){
		return uni.getStorageSync('isGoodType');
	},
	
	
	// 倒计时
	//param{Date}start 开始日期 2018-11-03 06:00:00
	//param{Date}end 结束日期 2018-11-03 06:00:00
	countTime:function(start, end) {
	    // 开始时间
	    var date = new Date(start.replace(/-/g, '/')); // ios 不支持2018-11-03 06:00:00
	    var now = date.getTime();
	    //设置截止时间
	    var endDate = new Date(end.replace(/-/g, '/'));
	    var end = endDate.getTime();
	    //时间差
	    var leftTime = 0;
	    var timer = null;
	    var d = 0,h = 0,m = 0,s = 0;
	    function count() {
	        now += 1000;
	        leftTime = end - now;
	        if (leftTime >= 0) {
	            d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
	            h = Math.floor(leftTime / 1000 / 60 / 60 % 24);
	            m = Math.floor(leftTime / 1000 / 60 % 60);
	            s = Math.floor(leftTime / 1000 % 60);
	            if (d < 10) d = '0' + d;
	            if (h < 10) h = '0' + h;
	            if (m < 10) m = '0' + m;
	            if (s < 10) s = '0' + s;
	        } else {
	            h = 0;
	            m = 0;
	            s = 0;
	            clearTimeout(timer);
	        }
	        timer = setTimeout(function() {
	            count();
	        }, 1000);
			return {d:d,h:h,m:m,s:s};
	    }
		return count();
	},
	mathFormat:function(data,digits){
		let num = data.toString();
		if(num.indexOf(".") == -1){
			num = num + '.00';
		}else{
			let arr = num.split('.');
			num = arr[0] + '.' + arr[1].substr(0,digits);
		}
		return num;
	},
	launchApp(d,plus) {
		// 打开第三方引用，ios 、 安卓有一些参数不一致，需要区分，详情：http://www.html5plus.org/doc/zh_cn/runtime.html#plus.runtime.launchApplication
		// 判断应用是否安装
		if (plus.runtime.isApplicationExist({ pname: d.pname, action: d.scheme })) {
			// 判断平台
			if (plus.os.name == 'Android') {
				plus.runtime.launchApplication(
					{
						pname: d.pname,
						action: d.scheme
					},
					function(e) {
						console.log('Open system default browser failed: ' + e.message);
					}
				);
			} else if (plus.os.name == 'iOS') {
				plus.runtime.launchApplication({ action: d.scheme }, function(e) {
					console.log('Open system default browser failed: ' + e.message);
				});
			}
		} else {
			uni.showModal({
				title: '提示',
				content: '程序未安装，请下载安装后重试',
				success: function(res) {
					if (res.confirm) {
						if(d.download_url) plus.runtime.openURL(d.download_url);
						console.log('用户点击确定');
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
		}
	},
	regPush(isLogin=false){
		setTimeout(function(){
			var client_id = uni.getStorageSync('client_id');
			if(!client_id){
				var pinf = plus.push.getClientInfo();  
				var client_id = pinf.clientid;//客户端标识
			}
			var user = uni.getStorageSync('userInfo');
			if(user) isLogin = true;
			if(client_id){
				henglang.post('app/registerPush',{client_id: client_id,os:plus.os.name},isLogin,function(res){
					uni.setStorage({
						key: 'client_id',
						data: client_id
					});
				});
			}
		},1000);
	},
	updataVersion:function(){
		// #ifdef APP-PLUS
		uni.hideLoading()
		plus.runtime.getProperty(plus.runtime.appid, function(widgetInfo) {
			henglang.get('app/update',{version: widgetInfo.version,name: widgetInfo.name,appid:widgetInfo.appid},false,function(res){
				var result = res.data;
				if (result.code == '0') {//更新
					switch(result.data.update){
						case '1':
							// uni.showModal({
							// 	title: '更新提示',
							// 	content: '检测到最新版本',
							// 	showCancel: false,
							// 	success: function (res) {
							// 		if (res.confirm) {
										
										
							// 		} else if (res.cancel) {
										
							// 		}
							// 	}
							// });
							uni.showLoading({
								title:'正在更新中，请稍后...',
								mask: true
							});
							uni.downloadFile({
								url: result.data.url,
								success: (downloadResult) => {
									if (downloadResult.statusCode === 200) {
										plus.runtime.install(downloadResult.tempFilePath, {
											force: false
										}, function() {
											uni.hideLoading();
											uni.showModal({
												title: '更新提示',
												content: '已更新成功，马上重启生效',
												showCancel: false,
												success: function (res) {
													plus.runtime.restart();
												}
											});
										}, function(e) {
											uni.hideLoading();
											uni.showModal({
												title: '更新提示',
												content: '安装失败，请到相应市场下载最新版本APP',
												showCancel: false,
												success: function (res) {
													plus.runtime.openURL(result.data.big_url);
												}
											});
										});
									}
								}
							});
							
						break;
						case '2':
							uni.reLaunch({
								url:'/pages/ydt/updataversion?url=' + result.data.url + '&content=' + result.data.content + '&version=' + result.data.version + '&time=' + result.data.time
							})
						break;
					}
				}
			});
		});
		// #endif
	}
}
export default henglang